using Dapper;
using MediatR;
using Microsoft.Extensions.Logging;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using RBAC.Write.Api.Application.Command.ERP.PurchasingManagement.RawMaterialSuppliers;
using System.Data;

namespace RBAC.Write.Api.Application.Handler.ERP.PurchasingManagement.RawMaterialSuppliers
{
    /// <summary>
    /// 逻辑删除供应商处理
    /// </summary>
    public class DeleteRawMaterialSupplierCommandHandlers : IRequestHandler<DeleteRawMaterialSupplierCommand, APIResult<int>>
    {
        private readonly IDbConnectionFactory _connectionFactory;
        private readonly ILogger<DeleteRawMaterialSupplierCommandHandlers> _logger;

        public DeleteRawMaterialSupplierCommandHandlers(IDbConnectionFactory connectionFactory, ILogger<DeleteRawMaterialSupplierCommandHandlers> logger)
        {
            _connectionFactory = connectionFactory;
            _logger = logger;
        }

        public async Task<APIResult<int>> Handle(DeleteRawMaterialSupplierCommand request, CancellationToken cancellationToken)
        {
            var res = new APIResult<int>();

            if (request.Id <= 0)
            {
                res.Code = APIEnums.Fail;
                res.Msg = "供应商ID无效";
                return res;
            }

            try
            {
                using var conn = _connectionFactory.CreateConnectionWithRetry();

                // 查询供应商状态与存在性
                var supplier = await conn.QueryFirstOrDefaultAsync<(int Status, int IsDeleted)?>(
                    new CommandDefinition(
                        "SELECT Status, IsDeleted FROM Supplier WHERE Id=@Id LIMIT 1",
                        new { request.Id }, cancellationToken: cancellationToken));

                if (supplier is null)
                {
                    res.Code = APIEnums.Fail;
                    res.Msg = "供应商不存在";
                    return res;
                }

                if (supplier.Value.IsDeleted == 1)
                {
                    res.Code = APIEnums.Fail;
                    res.Msg = "供应商已删除";
                    return res;
                }

                // 按约定：Status=0 为启用，不允许删除
                if (supplier.Value.Status == 0)
                {
                    res.Code = APIEnums.Fail;
                    res.Msg = "启用状态禁止删除";
                    return res;
                }

                using var tran = conn.BeginTransaction();
                try
                {
                    // 主表逻辑删除
                    var delSupplierSql = "UPDATE Supplier SET IsDeleted=1 WHERE Id=@Id AND IsDeleted=0";
                    var affected = await conn.ExecuteAsync(new CommandDefinition(delSupplierSql, new { request.Id }, tran, cancellationToken: cancellationToken));

                    // 关联表逻辑删除（若有数据）
                    var delBusinessSql = "UPDATE SupplierBusiness SET IsDel=1 WHERE Supplier_Id=@Supplier_Id AND IsDel=0";
                    var delFinanceSql  = "UPDATE SupplierFinance  SET IsDel=1 WHERE Supplier_Id=@Supplier_Id AND IsDel=0";
                    var delInvoiceSql  = "UPDATE SupplierInvoice  SET IsDel=1 WHERE Supplier_Id=@Supplier_Id AND IsDel=0";

                    await conn.ExecuteAsync(new CommandDefinition(delBusinessSql, new { Supplier_Id = request.Id }, tran, cancellationToken: cancellationToken));
                    await conn.ExecuteAsync(new CommandDefinition(delFinanceSql,  new { Supplier_Id = request.Id }, tran, cancellationToken: cancellationToken));
                    await conn.ExecuteAsync(new CommandDefinition(delInvoiceSql,  new { Supplier_Id = request.Id }, tran, cancellationToken: cancellationToken));

                    tran.Commit();

                    res.Code = APIEnums.Success;
                    res.Msg = "删除成功";
                    res.Data = affected; // 返回主表影响行数，0 或 1
                    return res;
                }
                catch (Exception ex)
                {
                    try { tran.Rollback(); } catch { }
                    _logger.LogError(ex, "删除供应商失败");
                    res.Code = APIEnums.Error;
                    res.Msg = $"删除失败: {ex.Message}";
                    return res;
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "数据库异常");
                res.Code = APIEnums.Error;
                res.Msg = $"数据库异常: {ex.Message}";
                return res;
            }
        }
    }
}
